package com.wondersgroup.fjzlpt.tbxt.service.impl.jc;

import java.util.Date;
import java.util.Map;
import java.util.UUID;

import com.quick.framework.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.quick.framework.boot.remoteResult.ResultObject;
import com.wondersgroup.fjzlpt.tbxt.dao.inter.jc.JcYbDao;
import com.wondersgroup.fjzlpt.tbxt.service.inter.jc.JcYbService;

@Service
public class JcYbServiceImpl implements JcYbService {

	@Autowired
	private JcYbDao jcYbDao;
	
	/**
	 * 保存：基层-综合信息月报
	 * @param map
	 * @return
	 */
	@Override
	public JSONObject save(Map<String, Object> map) {
		ResultObject ro = new ResultObject();
		String dataArr[] = map.get("NFYF").toString().split("-");
		map.put("NF", dataArr[0]);
		map.put("YF", dataArr[1]);
		map.put("ZT","1");

		String type = map.get("type").toString();
		if("add".equals(type)){
			this.insert(map, ro);
		}else{
			this.update(map, ro);
		}
		return (JSONObject)JSON.toJSON(ro);
	}
	
	/**
	 * 新增：基层-综合信息月报
	 * @param map
	 * @param ro
	 */
	private void insert(Map<String, Object> map, ResultObject ro){
		try {
			map.put("ID", UUID.randomUUID().toString());
			Date now = new Date();
			map.put("XZSJ", now);
			map.put("XSJ", now);
			jcYbDao.insert(map);
		} catch (Exception e) {
			ro.changeFaultState("综合信息月报保存失败！！");
			throw new ServiceException("ERR-JCYB-001","综合信息月报失败！！");
		}
	}
	
	/**
	 * 修改：基层-综合信息月报
	 * @param map
	 * @param ro
	 */
	private void update(Map<String, Object> map, ResultObject ro){
		try {
			map.put("XGSJ", new Date());
			jcYbDao.updateForPrimaryKey(map);
		} catch (Exception e) {
			ro.changeFaultState("综合信息月报修改失败！！");
			throw new ServiceException("ERR-JCYB-002","综合信息月报修改失败！！");
		}
	}

	/**
	 * 查询某机构填报记录
	 * @param map
	 * @return
	 */
	@Override
	public JSONObject queryOne(Map<String, String> map) {
		JSONObject result = new JSONObject();
		try {
			result = jcYbDao.queryOne(map);
			if(result.isEmpty()){
				result.put("JGMC" , map.get("YLJGMC"));
			}
			result.put("state","true");
		} catch (Exception e) {
			result.put("state","false");
			result.put("info","填报信息查询失败，请重试！");
			throw new RuntimeException("填报信息查询失败，请重试！", e);
		}
		return result;
	}

}
